/**
 * Project Name:jbase
 * File Name:Derby.java
 * Package Name:jbase.project.system.db
 * Date:2017年4月30日下午8:11:38
 * Copyright (c) 2017, chenzhou1025@126.com All Rights Reserved.
 *
*/

package jbase.project.system.db;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.spark.sql.jdbc.DerbyDialect;

/**
 * ClassName:Derby <br/>
 * Function: TODO ADD FUNCTION. <br/>
 * Reason: TODO ADD REASON. <br/>
 * Date: 2017年4月30日 下午8:11:38 <br/>
 *
 * @author Licheng
 * @version
 * @since JDK 1.8
 * @see
 */
public class Derby {

	private String driver = "org.apache.derby.jdbc.EmbeddedDriver";
	private String schema = "jdbc:derby:";
	private String db = null;
	private static String TABLE_TASK_DDL = "CREATE TABLE TASKS(ID INT NOT NULL,URL VARCHAR(1024) NOT NULL,STATUS VARCHAR(32) NOT NULL)";

	public Derby(String dbFilePath, boolean create) throws ClassNotFoundException, SQLException {
		Class.forName(driver);
		this.db = dbFilePath;
		Connection conn = DriverManager.getConnection(schema + db + (create ? ";create=true" : ""));
	}

	public Derby(String dbFilePath) throws ClassNotFoundException, SQLException {
		this(dbFilePath, false);
	}

	public void close() {
		try {
			DriverManager.getConnection("jdbc:derby:;shutdown=true");
		} catch (SQLException e) {
		}
	}

	public Connection getConnection() throws SQLException {
		Connection conn = DriverManager.getConnection(schema + db);
		return conn;
	}

	public static void main(String[] args) throws ClassNotFoundException, SQLException {
		Derby derby = new Derby("H:\\a.db", true);
		Connection conn = derby.getConnection();
		Connection conn2 = derby.getConnection();
		Connection conn3 = derby.getConnection();
		Connection conn4 = derby.getConnection();
		DatabaseMetaData dbMetadata = conn.getMetaData();
		ResultSet tables = dbMetadata.getTables(null, null, null, new String[] { "TABLE" });
		while (tables.next()) {
			System.out.println(tables.getString("TABLE_NAME"));
		}
		Statement s = conn.createStatement();
		s.executeUpdate(TABLE_TASK_DDL);
		conn.close();
		derby.close();
	}
}
